const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV,
})

exports.main = async (event) => {
	try {
		const wxContext = cloud.getWXContext()
		const { OPENID } = wxContext

		const Users = cloud.database().collection('gn_user')
		const Spaces = cloud.database().collection('gn_space')

		const { name } = event

		const timestamp = new Date().getTime()

		const newSpaceRes = await Spaces.add({
			data: {
				subscriber: [],
				name,
				article: [],
				description: '',
				author: OPENID,
				last_modified_time: timestamp,
				create_time: timestamp,
				cover: '',
			},
		})

		const newSpaceId = newSpaceRes._id

		const user = await Users.doc(OPENID).get()
		const space = await Spaces.doc(newSpaceId).get()

		const userSpace = user.data.space || []
		userSpace.push({
			_id: space.data._id,
			name: space.data.name,
		})

		await Users.doc(OPENID).update({
			data: {
				space: userSpace,
			},
		})

		const newUserInfo = await Users.doc(OPENID).get()
		const newSpaceInfo = await Spaces.doc(newSpaceId).get()

		return {
			code: 0,
			msg: '创建成功',
			data: {
				user: newUserInfo.data,
				space: newSpaceInfo.data,
			},
		}
	} catch (err) {
		throw err
	}
}
